package edu.zut.securityquestion.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.zut.securityquestion.generator.domain.Danxuan;
import edu.zut.securityquestion.generator.domain.Duoxuan;
import edu.zut.securityquestion.generator.domain.History;
import edu.zut.securityquestion.generator.domain.Panduan;
import edu.zut.securityquestion.generator.service.impl.DanxuanServiceImpl;
import edu.zut.securityquestion.generator.service.impl.DuoxuanServiceImpl;
import edu.zut.securityquestion.generator.service.impl.HistoryServiceImpl;
import edu.zut.securityquestion.generator.service.impl.PanduanServiceImpl;
import edu.zut.securityquestion.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;
import sun.awt.image.ImageWatched;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.StringReader;
import java.sql.Date;
import java.util.*;

/**
 * Author Hys
 * Date 2021/12/2 18:08
 * Project securityquestion
 */
@Controller
@RequestMapping("/question")
@CrossOrigin
public class QuestionController {

    @Autowired
    DanxuanServiceImpl danxuanService;

    @Autowired
    DuoxuanServiceImpl duoxuanService;

    @Autowired
    PanduanServiceImpl panduanService;

    @Autowired
    HistoryServiceImpl historyService;

    List<Question> questions = null;

    @RequestMapping("/main")
    public String main(Model model, @RequestParam(required = false) String word){
        QueryWrapper<Danxuan> danxuanQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Duoxuan> duoxuanQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Panduan> panduanQueryWrapper = new QueryWrapper<>();

        System.out.println("查询词"+word);

        List<Danxuan> danxuans = new ArrayList<>();
        List<Duoxuan> duoxuans = new ArrayList<>();
        List<Panduan> panduans = new ArrayList<>();

        if(word!=null){
            danxuanQueryWrapper.like("question", word);
            duoxuanQueryWrapper.like("question", word);
            panduanQueryWrapper.like("question", word);

            danxuans = danxuanService.list(danxuanQueryWrapper);
            duoxuans = duoxuanService.list(duoxuanQueryWrapper);
            panduans = panduanService.list(panduanQueryWrapper);
        }

        model.addAttribute("danxuans", danxuans);
        model.addAttribute("duoxuans", duoxuans);
        model.addAttribute("panduans", panduans);
        return "main";
    }

    @RequestMapping("/api/getAllQuestions")
    @ResponseBody
    public String getAllQuestions(){
        if(questions == null){
            questions = new ArrayList<>();
            danxuanService.list().forEach(item->{
                questions.add(new Question(item.getQuestion()));
            });
            duoxuanService.list().forEach(item->{
                questions.add(new Question(item.getQuestion()));
            });
            panduanService.list().forEach(item->{
                questions.add(new Question(item.getQuestion()));
            });
        }
        return JSON.toJSONString(questions);
    }

    class Question{
        String value;

        public Question(String value){
            setValue(value);
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }

    @RequestMapping("/api/danxuanresult")
    @ResponseBody
    public String danxuanresult(@RequestParam(required = false) String word, HttpServletRequest request){

        System.out.println("查询词"+word);

        String ip = IpUtil.getIpAddr(request);
        System.out.println(ip);
        History history = new History();
        history.setIp(ip);
        history.setTime(new Date(System.currentTimeMillis()));
        history.setWord(word);
        historyService.save(history);

        QueryWrapper<Danxuan> danxuanQueryWrapper = new QueryWrapper<>();

        List<Danxuan> danxuans = new ArrayList<>();
        HashMap<Danxuan, Integer> map = new HashMap<>();

        StringReader sr=new StringReader(word);
        IKSegmenter ik=new IKSegmenter(sr, true);
        Lexeme lex = null;
        while(true){
            try {
                if ((lex = ik.next()) == null) {
                    break;
                }
                danxuanQueryWrapper.like("question", lex.getLexemeText());
                danxuans.addAll(danxuanService.list(danxuanQueryWrapper));
                danxuanQueryWrapper.clear();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        for (int i = 0; i < danxuans.size(); i++) {
            if(map.containsKey(danxuans.get(i))){
                map.put(danxuans.get(i), map.get(danxuans.get(i)) + 1);
            }else{
                map.put(danxuans.get(i),1);
            }
        }

        List<Map.Entry<Danxuan, Integer>> res =new ArrayList<Map.Entry<Danxuan, Integer>>(map.entrySet());
        Collections.sort(res, new Comparator<Map.Entry<Danxuan, Integer>>() {
            @Override
            public int compare(Map.Entry<Danxuan, Integer> o1, Map.Entry<Danxuan, Integer> o2) {
                if(o1.getValue() > o2.getValue()){
                    return -1;
                } else if (o1.getValue() < o2.getValue()) {
                    return 1;
                }
                return 0;
            }
        });

        danxuans.clear();
        for (int i = 0; i < 3; i++) {
            if(i>res.size()-1){
                break;
            }
            danxuans.add(res.get(i).getKey());
        }

        return JSON.toJSONString(danxuans, SerializerFeature.DisableCircularReferenceDetect);
    }

    @RequestMapping("/api/duoxuanresult")
    @ResponseBody
    public String duoxuanresult(@RequestParam(required = false) String word){
        QueryWrapper<Duoxuan> duoxuanQueryWrapper = new QueryWrapper<>();

        List<Duoxuan> duoxuans = new ArrayList<>();
        HashMap<Duoxuan, Integer> map = new HashMap<>();

        StringReader sr=new StringReader(word);
        IKSegmenter ik=new IKSegmenter(sr, true);
        Lexeme lex = null;
        while(true){
            try {
                if ((lex = ik.next()) == null) {
                    break;
                }
                duoxuanQueryWrapper.like("question", lex.getLexemeText());
                duoxuans.addAll(duoxuanService.list(duoxuanQueryWrapper));
                duoxuanQueryWrapper.clear();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        for (int i = 0; i < duoxuans.size(); i++) {
            if(map.containsKey(duoxuans.get(i))){
                map.put(duoxuans.get(i), map.get(duoxuans.get(i)) + 1);
            }else{
                map.put(duoxuans.get(i),1);
            }
        }

        List<Map.Entry<Duoxuan, Integer>> res =new ArrayList<Map.Entry<Duoxuan, Integer>>(map.entrySet());
        Collections.sort(res, new Comparator<Map.Entry<Duoxuan, Integer>>() {
            @Override
            public int compare(Map.Entry<Duoxuan, Integer> o1, Map.Entry<Duoxuan, Integer> o2) {
                if(o1.getValue() > o2.getValue()){
                    return -1;
                } else if (o1.getValue() < o2.getValue()) {
                    return 1;
                }
                return 0;
            }
        });

        duoxuans.clear();
        for (int i = 0; i < 3; i++) {
            if(i>res.size()-1){
                break;
            }
            duoxuans.add(res.get(i).getKey());
        }

        return JSON.toJSONString(duoxuans, SerializerFeature.DisableCircularReferenceDetect);
    }

    @RequestMapping("/api/panduanresult")
    @ResponseBody
    public String panduanresult(@RequestParam(required = false) String word){
        QueryWrapper<Panduan> panduanQueryWrapper = new QueryWrapper<>();

        List<Panduan> panduans = new ArrayList<>();
        HashMap<Panduan, Integer> map = new HashMap<>();

        StringReader sr=new StringReader(word);
        IKSegmenter ik=new IKSegmenter(sr, true);
        Lexeme lex = null;
        while(true){
            try {
                if ((lex = ik.next()) == null) {
                    break;
                }
                panduanQueryWrapper.like("question", lex.getLexemeText());
                panduans.addAll(panduanService.list(panduanQueryWrapper));
                panduanQueryWrapper.clear();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        for (int i = 0; i < panduans.size(); i++) {
            if(map.containsKey(panduans.get(i))){
                map.put(panduans.get(i), map.get(panduans.get(i)) + 1);
            }else{
                map.put(panduans.get(i),1);
            }
        }

        List<Map.Entry<Panduan, Integer>> res =new ArrayList<Map.Entry<Panduan, Integer>>(map.entrySet());
        Collections.sort(res, new Comparator<Map.Entry<Panduan, Integer>>() {
            @Override
            public int compare(Map.Entry<Panduan, Integer> o1, Map.Entry<Panduan, Integer> o2) {
                if(o1.getValue() > o2.getValue()){
                    return -1;
                } else if (o1.getValue() < o2.getValue()) {
                    return 1;
                }
                return 0;
            }
        });

        panduans.clear();
        for (int i = 0; i < 3; i++) {
            if(i>res.size()-1){
                break;
            }
            panduans.add(res.get(i).getKey());
        }

        return JSON.toJSONString(panduans, SerializerFeature.DisableCircularReferenceDetect);
    }

}
